
document.write('<script type="text/javascript" src="'+jsHostBase+'js/uploader/uploader.js"></script>');

/**
 * 必多盈文本编辑器
 */
var ueEditor = new function () {
    /**
    * 图片管理插件
    */
    var editorPlugins = {
        btnImg: {
            c: 'xheIcon xheBtnImg',
            t: '插入图片',
            h: 0,
            e: function () {
                var _this = this;
                _this.params = _this.settings.img_upload_params;
                var html = '';  // 图片库显示框架
                html += '<div id="bd-uploader">'
                      + '	<div class="flash" id="fsUploadProgress"></div>'
                      + '   <div id="buttonArea">'
                      + '       <input class="fl" type="checkbox" name="select-all-pic" id="select-all-pic" />'
                      + '       <a href="javascript:void(0);" id="get-pics" class="up-btn fl" title="点击这里把选中的图片插入到编辑器中"><span><div id="div-get-pics">引用图片</div></span></a>'
                      + '       <a href="javascript:void(0);" id="del-pics" class="up-btn fl" title="点击这里批量删除图片"><span><div id="div-del-pics">删除图片</div></span></a>'
                      + '       <a href="javascript:void(0);" id="addFiles" class="up-btn fl" title="点击这里上传图片"><span><div id="divAddFiles">添加文件</div></span></a>'
                      + '   </div>'
                      + '   <div id="photo-list">'
                      + '       <span class="fl note" style="padding:0 0 0 10px;">1.双击图片把该图片插入编辑器； 2.单击选中图片后点击"引用图片"把选中的图片插入编辑器中。 </span>'
                      + '       <ul><div class="floor-loading"></div></ul>'
                      + '   </div>'
                      + '   <div id="photo-paging">'
                      + '     <a href="#" onclick="load();return false;">头页</a>'
                      + '     <a href="#" onclick="load();return false;">上一页</a>'
                      + '     <a href="#" onclick="load();return false;">1</a>'
                      + '     <a href="#" onclick="load();return false;">2</a>'
                      + '     <a href="#" onclick="load();return false;">3</a>'
                      + '     <a href="#" onclick="load();return false;">4</a>'
                      + '     <a href="#" onclick="load();return false;">下一页</a>'
                      + '     <a href="#" onclick="load();return false;">尾页</a>'
                      + '   </div>'
                      + '</div>';

                creatPopBox('', 685, 420, html, 'buttonArea');

                // 上传图片成功后处理返回数据
                _this.uploadFinishHandler = function (file, r) {					
                    try {
                        eval('var r = ' + r);
						if(!checkAjaxReturn(r)) return false;
                    } catch (e) {
                        alert(e+ "\n" + r);
                    }
					$('#no-upload-pic').remove();

                    //alert(r.title);
                    html = '<li class="checked" id="photo-list-item-' + r.img_id + '">'
						 + '  <input type="checkbox" value="' + r.img + '" id="' + r.img_id + '" name="check-pic[' + r.img_id + ']" class="check-pic" checked="checked" />'
						 + '  <p><img class="pic" src="' + r['thumb'] + '" width="98" height="98" ></p>'
						 + '  <p id="checked-pic-title-' + r.img_id + '" class="pic-title">' + r['title'] + '</p>'
						 + '</li>';
                    $('#photo-list ul').prepend(html);

                    // 点击图片选中和去掉选中
                    $('#photo-list li').unbind();
                    $('#photo-list li').click(function () {
                        if ($(this).hasClass('checked')) {
                            $(this).find('.check-pic').removeAttr('checked');
                            $(this).removeClass('checked');
                        } else {
                            $(this).find('.check-pic').attr('checked', 'checked');
                            $(this).addClass('checked');
                        }
                    });

                    // 双击图片插入编辑框
                    $('#photo-list img').unbind();
                    $('#photo-list img').dblclick(function () {
                        var parent = $(this).parent().parent();
                        var src = parent.find('.check-pic').val();
                        var title = parent.find('.pic-title').text();
                        _this.pasteHTML('<img src="' + src + '" alt="' + title + '" />');
                        removePopBox();
                    });
                }


                var editorSwfu;
                //$(function() {
                var settings = {
                    flash_url: jsHostBase+'js/uploader/swfupload.swf',
                    upload_url: uploadUrl + ((uploadUrl.indexOf('?') == -1) ? '?' : '&') + json2Reqstr(_this.params),
                    post_params: {"UESID" : getCookie("UESID")}, // json格式
                    file_size_limit: "500 K",
                    file_types: "*.jpg;*.gif;*.png",
                    file_types_description: "图片",
                    file_upload_limit: 20,
                    file_queue_limit: 0,
                    custom_settings: { progressTarget: "fsUploadProgress" },
					file_post_name : "file",

                    debug: false,

                    // Button settings
                    button_image_url: jsHostBase+"js/uploader/images/add.gif",
                    button_width: 80,
                    button_height: 17,
                    button_window_mode: SWFUpload.WINDOW_MODE.TRANSPARENT,
                    button_cursor: SWFUpload.CURSOR.HAND,
                    button_placeholder_id: "divAddFiles",
                    button_text: '<span class="theFont">上传图片</span>',
                    button_text_style: ".theFont {color:#006699; }",
                    button_text_left_padding: 20,
                    button_text_top_padding: 0,

                    // The event handler functions are defined in handlers.js
                    file_queued_handler: fileQueued,
                    file_queue_error_handler: fileQueueError,
                    file_dialog_complete_handler: fileDialogComplete,
                    upload_start_handler: uploadStart,
                    upload_progress_handler: uploadProgress,
                    upload_error_handler: uploadError,
                    upload_success_handler: _this.uploadFinishHandler,
                    upload_complete_handler: uploadComplete,
                    queue_complete_handler: queueComplete
                };
				
				for(var i in _this.params) {
					settings.post_params[encodeURIComponent(i)] = encodeURIComponent(_this.params[i] || '');
				}
        
				//alert(settings.upload_url);
				
				editorSwfu = new SWFUpload(settings);
								
                //});

                _this.pageSize = 24;
                _this.page = 1;
                _this.pages = 1;
                _this.pagingFirst = 1;
                _this.pagingLast = 1;
                _this.pagingPre = 1;
                _this.pagingNext = 1;
                _this.json = null;
				
                /**
                * 显示分页导航条
                */
                _this.showPaging = function () {
                    var paging = '';
                    var r = _this.json;
                    _this.pages = r.totals == 0 ? 0 : Math.ceil(parseInt(r.totals) / _this.pageSize); // 总页数

                    if (_this.page < 1) _this.page = 1;  // 页码从0开始
                    if (_this.page > _this.pages) _this.page = _this.pages;

                    _this.pagingFirst = _this.page - 5; // 第一页
                    _this.pagingLast = _this.page + 5;  // 最后一页
                    _this.pagingPre = _this.page - 1;   // 上一页
                    _this.pagingNext = _this.page + 1;  // 下一页

                    if (_this.pagingFirst < 1) _this.pagingFirst = 1;
                    if (_this.pagingPre < 1) _this.pagingPre = 1;
                    if (_this.pagingLast > _this.pages) _this.pagingLast = _this.pages;
                    if (_this.pagingNext > _this.pages) _this.pagingNext = _this.pages;

                    paging += "<a href=\"javascript:;\" page=\"1\">[首页]</a>";
                    paging += "<a href=\"javascript:;\" page=\"" + _this.pagingPre + "\">[上一页]</a>";

                    for (var i = _this.pagingFirst; i <= _this.pagingLast; i++) {
                        var current = '';
                        if (i == _this.page) current = 'class="current"';
                        paging += "<a href=\"javascript:;\" page=\"" + i + "\" " + current + ">[" + (i) + "]</a>";
                        current = '';
                    }

                    paging += "<a href=\"javascript:;\" page=\"" + _this.pagingNext + "\">[下一页]</a>";
                    paging += "<a href=\"javascript:;\" page=\"" + (_this.pages) + "\">[尾页]</a>";
                    paging += ' 共' + _this.pages + '页,' + r.totals + '张';

                    $('#photo-paging').html(paging);

                    $('#photo-paging a').unbind();
                    $('#photo-paging a').click(function () { _this.loadPage($(this).attr('page')); });
                }

                /**
                * 显示已上传的图片列表
                */
                _this.showPhotos = function () {
                    var r = _this.json;
					
                    if (r.err) {
                        // 没有权限则转到登录页
                        if ('denned' == r.err) {
                            parent.window.location = ''; // 转到登录页
                            return;
                        }

                        // 显示错误信息
                        $('#photo-list ul').html('<p class="err">' + r.err + '</p>');
                        return;
                    }

                    var html = '';
                    var images = r.images;
                    if (images.length <= 0) {
						$('#photo-list ul').html('<p id="no-upload-pic">您还没有上传图片！</p>');
                    } else {
                        html = '';
                        for (var i in images) {
                            html += '<li id="photo-list-item-' + images[i]['img_id'] + '">'
								  + '  <input class="check-pic" type="checkbox" name="check-pic[' + images[i]['img_id'] + ']" id="' + images[i]['img_id'] + '" value="' + images[i]['img'] + '" />'
								  + '  <p><img class="pic" src="' + images[i]['thumb'] + '" ></p>'
								  + '  <p id="checked-pic-title-' + images[i]['img_id'] + '" class="pic-title">' + images[i]['title'] + '</p>'
								  + '</li>';
                        }

                        $('#photo-list ul').html(html);
                    }

                    //alert(html);

                    // 点击图片选中和去掉选中
                    $('#photo-list li').click(function () {
                        if ($(this).hasClass('checked')) {
                            $(this).find('.check-pic').removeAttr('checked');
                            $(this).removeClass('checked');
                        } else {
                            $(this).find('.check-pic').attr('checked', 'checked');
                            $(this).addClass('checked');
                        }
                    });

                    // 双击图片插入编辑框
                    $('#photo-list img').dblclick(function () {
                        var parent = $(this).parent().parent();
                        var src = parent.find('.check-pic').val();
                        var title = parent.find('.pic-title').text();
                        _this.pasteHTML('<img src="' + src + '" alt="' + title + '" />');
                        removePopBox();
                    });

                    // 选中或去掉所有选择的图片
                    $('#bd-uploader #select-all-pic').click(function () {
                        if (!$(this).attr('checked')) {
                            $('#photo-list input.check-pic').removeAttr('checked')
                            $('#photo-list li').removeClass('checked')
                        } else {
                            $('#photo-list input.check-pic').attr('checked', 'checked')
                            $('#photo-list li').addClass('checked')
                        }
                    });

                    // 删除图片
                    $('#del-pics').click(function () {
                        var pics = new Array();
                        var picsData = new Array();
                        var obj = $('#photo-list input.check-pic:checked');
                        if (obj.length <= 0) {
                            alert('请选择图片');
                            return;
                        }
						
                        if (!confirm('您确定要删除选中的图片吗？')) {
                            return false;
                        }

                        for (var i = 0; i < obj.length; i++) {
                            pics.push(obj[i].id);
                            picsData.push('items_id[]=' + obj[i].id);
                        }

                        $.ajaxf.post(delImgUrl, picsData.join('&'), function (r) {
                            try {
                                eval('var r=' + r);
                                if (typeof r == 'object' && r.err.length == 0) {
                                    _this.loadPage(_this.page);
                                }
                            } catch (e) {
                                alert(r);
                            }

                        }, 'form');
                    });

                    // 批量引用图片
                    $('#get-pics').click(function () {
                        var obj = $('#photo-list input.check-pic:checked');
                        if (obj.length <= 0) {
                            alert('请选择图片');
                            return;
                        }

                        var html = '';
                        for (var i = 0; i < obj.length; i++) {
                            html += '<img src="' + obj[i].value + '" alt="' + $('#checked-pic-title-' + obj[i].id).text() + '" /><br />';
                        }

                        _this.pasteHTML(html);
                        removePopBox();
                    });
                }

                /**
                * 加载图片库
                *
                * @param int page 页码
                * @param int pageSize 每页记录数
                */
                _this.loadPage = function (page) {
                    _this.page = parseInt(page);

                    // 解除绑定元素
                    $('#select-all-pic').removeAttr('checked');
                    $('#photo-list li').unbind();
                    $('#photo-list img').unbind();
                    $('#bd-uploader #select-all-pic').unbind();
                    $('#del-pics').unbind();
                    $('#get-pics').unbind();

                    $('#photo-list ul').html('<div class="floor-loading"></div>');
                    $.ajaxf.getJSON(imgListUrl, 'page=' + _this.page + '&pageSize=' + _this.pageSize + '&rand='+Math.random(), function (r) {
						//alert(typeof r);
						if(typeof r === 'string') {
							alert('服务器端出错');
							return false;
						}
						_this.json = r;
                        _this.showPaging();
                        _this.showPhotos();
                        r = null;
                    });
                }

                // 载入完成后
                $.ajaxf.ready(function () {
                    _this.loadPage(1);
                });
            }
        }
    }
    // End 图片管理插件

    this.apply = function (id, params) {

        var opts = {
            img_upload_params: {},
            skin: 'o2007blue',
            plugins: editorPlugins,
            tools: 'Pastetext,|,Fontface,FontSize,Bold,Italic,Underline,Strikethrough,FontColor,BackColor,Removeformat,|,Align,List,Indent,Outdent,|,Link,Unlink,btnImg,map,Table,|,Source,|,About'
        };
		
        // 传参给 上传插件
        if (typeof params != undefined) {
            for (var i in params) {
				params[i] = params[i] || '';
                opts.img_upload_params[i] = params[i];
            }
        }
		
		try {
		    return $(id).xheditor(opts);
		} catch (e) {
			alert(e);
		}
    }
}

